;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Stock.DeliveryOrderIn", [])
        .controller("DeliveryOrderInCtrl", ["$scope", "$state", "ybWidget", "ybHttp", "MESG_TYPE", "$filter", "$timeout", "Upload", "UserContextService", "EventBus", function ($scope, $state, ybWidget, ybHttp, MESG_TYPE, $filter, $timeout, Upload, UserContextService, EventBus) {
            $scope.activeFlag = [true, false, false];
            $scope.datePickerFlag = [false, false];
            $scope.markInfo = {
                allCheckedBill: false,
                allCheckedMaterial: false,
                curRow: -1
            };
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.submitted = false;
            $scope.condition = {};
            $scope.toolbarConfig = {
                showAdvanceSearch: false,
                showColConfig: false,
                showMateriel: false
            };
            $scope.dataList = [];
            $scope.tbConf = {
                fixedWidth: 210,
                scrollWidth: 830,
                tableCol: [
                    {
                        type: "",
                        name: "入库单号",
                        dataField: "deliveryOrder",
                        width: 180,
                        isShow: true,
                        isFixed: false,
                        clickFn: "viewDetail",
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "配送指令",
                        dataField: "deliveryInstructionNo",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "仓库",
                        dataField: "warehouseCode",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "制单人",
                        dataField: "createName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "制单时间",
                        dataField: "createDateShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "入库状态",
                        dataField: "stateShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "过账状态",
                        dataField: "postingStateShow",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        width: 170,
                        isShow: true,
                        isFixed: true,
                        toSort: false,
                        sortType: ""
                    }
                ]
            };
            $scope.viewTbConf = {
                scrollWidth: 1180,
                tableCol: [
                    {
                        name: "零件编号",
                        width: 120,
                        dataField: "materialNo",
                        isShow: true
                    },
                    {
                        name: "零件中文名",
                        width: 200,
                        dataField: "materialName",
                        isShow: true
                    },
                    {
                        name: "收货零件凭证",
                        width: 150,
                        dataField: "inVoucher",
                        isShow: true
                    },
                    {
                        name: "发货零件凭证",
                        width: 150,
                        dataField: "outVoucher",
                        isShow: true
                    },
                    {
                        name: "行号",
                        width: 80,
                        dataField: "rowNo",
                        isShow: true
                    },
                    {
                        name: "入库数量",
                        width: 100,
                        dataField: "amount",
                        isShow: true
                    },
                    {
                        name: "实际入库数量",
                        width: 120,
                        dataField: "realAmount",
                        isShow: true
                    },
                    {
                        name: "未过账数量",
                        width: 100,
                        dataField: "unpostedQty",
                        isShow: $scope.isDL || $scope.isZHL || $scope.isYH,
                    },
                    {
                        name: "SAP库存数量",
                        width: 120,
                        dataField: "sapInventory",
                        isShow: $scope.isDL || $scope.isZHL || $scope.isYH,
                    },
                    {
                        name: "入库状态",
                        width: 100,
                        dataField: "stateShow",
                        isShow: true
                    },
                    {
                        name: "SAP同步状态",
                        width: 120,
                        dataField: "sapSynStatusShow",
                        isShow: true
                    },
                    {
                        name: "过账状态",
                        width: 100,
                        dataField: "postingStateShow",
                        isShow: true
                    }
                ]
            };
            $scope.detailInfo = {};
            $scope.orderObj = {};
            $scope.inState = [
                {id: 0, name: "未入库"},
                {id: 1, name: "部分入库"},
                {id: 2, name: "已入库"},
                {id: 3, name: "强制结单"}
            ];
            $scope.postingState = [
                {id: 0, name: "未过账"},
                {id: 1, name: "部分过账"},
                {id: 2, name: "已过账"}
            ];
            $scope.exportParam = {
                sectionUrl: ybHttp.RequestUrl("device", "/deliveryInstruction/export"),
                sectionParam: {ids: []},
                allUrl: ybHttp.RequestUrl("device", "/deliveryInstruction/exportAll")
            };
            var sortParam = "";
            var sortFiled = {};

            var btnPermissionCode = {
                deliveryOrderInAdd: window.ActionCode.deliveryOrderInAdd,
                deliveryOrderInPosting: window.ActionCode.deliveryOrderInPosting,
                deliveryOrderInPrint: window.ActionCode.deliveryOrderInPrint,
                deliveryOrderInExport: window.ActionCode.deliveryOrderInExport,
                mandatoryFinish: window.ActionCode.deliveryOrderInMandatoryFinish,
                deliveryOrderInRevoke: window.ActionCode.deliveryOrderInRevoke,
                deliveryOrderInChongxiao: window.ActionCode.deliveryOrderInChongxiao
            };

            $scope.btnPermission = {
                deliveryOrderInAdd: true,
                deliveryOrderInPosting: true,
                deliveryOrderInPrint: true,
                deliveryOrderInExport: true,
                mandatoryFinish: true,
                deliveryOrderInRevoke: true,
                deliveryOrderInChongxiao: true
            };

            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
            }

            $scope.setFixedWidth = function () {
                $scope.tbStyle = {
                    fixedWidth: {left: $scope.tbConf.fixedWidth + "px"}
                };
            };

            $scope.changeTab = function (index) {
                $scope.activeFlag = [false, false, false];
                $scope.activeFlag[index] = true;
                $scope.submitted = false;
                switch (index) {
                    case 0:
                        initData();
                        break;
                    case 1:
                        break;
                    case 2:
                        break;
                    default:
                        break;
                }
            };

            function initData() {
                $scope.detailInfo = {};
                $scope.orderObj = {};
                $scope.tabFlag = {};
                $scope.markInfo.allCheckedBillDetail = false;
                $scope.markInfo.allCheckedMaterial = false;
                $scope.toolbarConfig.showMateriel = false;
                $scope.innerOrder = {
                    item: null
                };
            }

            function getDataList(curPage) {
                $scope.markInfo = {
                    allCheckedBill: false,
                    allCheckedMaterial: false,
                    curRow: -1
                };
                $scope.exportParam.sectionParam.ids = [];
                var service = "device";
                var reqUrl = "/deliveryInstruction/list";
                var param = {};
                param.pageSize = $scope.pageInfo.pageSize;
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                param.pageNum = $scope.pageInfo.curPage;
                param.filters = angular.copy($scope.condition);
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                        item.createDateShow = $filter("YbDate")(item.createDate,'yyyy-MM-dd HH:mm:ss');
                        item.stateShow = $filter("ProgressStatus")(item.state, "inDepot");
                        item.postingStateShow = $filter("ProgressStatus")(item.postingState, "posting");
                    });
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                    $scope.dataList = resp.value.list;
                });
            }

            $scope.toSort = function (config, index) {
                if (!config[index].toSort) {
                    return;
                }
                var sortType = ybWidget.ToSort(config, index);
                sortFiled = config[index];
                sortParam = sortFiled.sortField + " " + sortType;
                // getDataList(1);
            };

            function clearSortParam() {
                sortParam = "";
                if (angular.isDefined(sortFiled.sortType)) {
                    sortFiled.sortType = ""
                }
            }

            $scope.selectRow = function (index) {
                $scope.markInfo.curRow = index
            };

            function viewSapErrorMsg(item) {
                ybWidget.ShowMessage(item.sapErrorMsg, MESG_TYPE.Note);
            }

            $scope.tdClick = function (item, fnType) {
                switch (fnType) {
                    case "viewDetail":
                        $scope.viewDetail(item);
                        break;
                    case "viewSapErrorMsg":
                        viewSapErrorMsg(item);
                        break;
                    default:
                        break;
                }
            };

            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig["show" + toolbar] = true;
                    });
                }
            };

            $scope.switchDataPicker = function (index) {
                $scope.datePickerFlag = [false, false];
                if (angular.isDefined(index)) {
                    $scope.datePickerFlag[index] = true;
                }
            };

            $scope.checkDate = function (obj, startFiled, endFiled) {
                var timeFormatObj = ybWidget.CheckDate(obj[startFiled], obj[endFiled]);
                if (!!timeFormatObj.tStart) {
                    obj[startFiled] = timeFormatObj.tStart;
                }
                if (!!timeFormatObj.tEnd) {
                    obj[endFiled] = timeFormatObj.tEnd;
                }
            };

            $scope.search = function (curpage) {
                getDataList(curpage);
            };

            $scope.reset = function () {
                $scope.condition = {};
            };

            function getBillIds() {
                $scope.exportParam.sectionParam.ids = [];
                angular.forEach($scope.dataList, function (item) {
                    if (!!item.isChecked) {
                        $scope.exportParam.sectionParam.ids.push(item.id);
                    }
                });
            }

            $scope.selectSingle = function (item, list, type) {
                if (!item.isChecked) {
                    $scope.markInfo["allChecked" + type] = false;
                } else {
                    if (!checkAll(list)) {
                        $scope.markInfo["allChecked" + type] = false;
                    } else {
                        $scope.markInfo["allChecked" + type] = true;
                    }
                }
                getBillIds();
            };

            function checkAll(list) {
                var selectAll = false;
                for (var i = 0, len = list.length; i < len; i++) {
                    if (!list[i].isChecked) {
                        selectAll = false;
                        break;
                    }
                    selectAll = true;
                }
                return selectAll;
            }

            $scope.selectAll = function (list, type) {
                angular.forEach(list, function (item) {
                    item.isChecked = $scope.markInfo["allChecked" + type];
                });
                getBillIds();
            };

            $scope.tabFlag = {};
            var tabFlag = {
				0: "新增",
				1: "编辑"
			};

            $scope.addData = function () {
                $scope.tabFlag.type = 0;
                $scope.tabFlag.name = tabFlag[0];
                $scope.changeTab(1);
            };

            $scope.editData = function (item) {
                getDetail(item.id).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.tabFlag.type = 1;
                    $scope.tabFlag.name = tabFlag[1];
                    $scope.detailInfo = data.headerInfo;
                    $scope.changeTab(1);
                });
            };

            function getDetail(billId) {
                var service = "device";
                var reqUrl = "/deliveryInstruction/item";
                var param = {};
                param.id = billId;
                return ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return false;
                    }
                    return resp.value;
                });
            }

            $scope.viewDetail = function (item) {
                getDetail(item.id).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.changeTab(2);
                    $scope.orderObj = data;
                    angular.forEach($scope.orderObj.detailList, function (item) {
                        item.isChecked = false;
                        item.stateShow = $filter("ProgressStatus")(item.state, "inDepot");
                        item.postingStateShow = $filter("ProgressStatus")(item.postingState, "posting");
                        item.sapSynStatusShow = $filter("ProgressStatus")(item.sapSynStatus, "synStatus");
                    });
                });
            };

            $scope.printBill = function (item) {
                var id = item.id;
                var billIds = [];
                billIds.push(id);
                var param = {
                    billId: billIds,
                    printType: "DeliveryOrderIn"
                };
                ybWidget.SetIsPrintOrPreview(param);
            };

            $scope.materielDebit = function (billId, item) {
                item.postingDisabled = true;
                var service = "device";
                var reqUrl = "/deliveryInstruction/posting";
                var param = {};
                param.detailId = item.id;
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        item.postingDisabled = false;
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    getDetail(billId);
                });
            };

            $scope.batchMaterielDebit = function () {
                const selectedDatas = $scope.orderObj.detailList.filter(od => od.isChecked);
                if (selectedDatas.length === 0) {
                    ybWidget.ShowToaster('error', '请选择需要过账的行');
                    return;
                }

                var service = "device";
                var reqUrl = "/deliveryInstruction/batchPosting";
                ybHttp.Post(service, reqUrl, { detailIds: selectedDatas.map(od => od.id) }).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        item.postingDisabled = false;
                        return;
                    }
                    const respValTmp = resp.value || [];
                    if (respValTmp.length > 0) {
                        ybWidget.ShowMessage(respValTmp.join("<br/>"),  MESG_TYPE.Error, {isHtml: true})
                    } else {
                        ybWidget.ShowToaster('success', '操作成功');
                    }
                    
                    if (respValTmp.length != selectedDatas.length) {
                        // 有过账成功的行，刷新页面
                        $scope.viewDetail({id: $scope.orderObj.headerInfo.id });
                    }
                });
            };

            $scope.selectWarehouse = function () {
                ybWidget.WarehouseSelector().then(function (data) {
                    if (!!$scope.detailInfo.warehouseCode && (data.warehouseCode !== $scope.detailInfo.warehouseCode)) {
                        $scope.detailInfo.inArea = "";
                        $scope.detailInfo.sapInArea = "";
                    }
                    $scope.detailInfo.warehouseCode = data.warehouseCode;
                })
            };

            $scope.clearWarehouse = function () {
                $scope.detailInfo.warehouseCode = "";
                $scope.detailInfo.inArea = "";
                $scope.detailInfo.sapInArea = "";
            };

            $scope.selectArea = function () {
                if (!$scope.detailInfo.warehouseCode) {
                    ybWidget.ShowToaster('error', '请选择仓库');
                    return;
                }
                var param = {};
                param.warehouseCode = $scope.detailInfo.warehouseCode;
                ybWidget.DepotAreaSelector(param).then(function (data) {
                    $scope.detailInfo.inArea = data.areaCode;
                    $scope.detailInfo.sapInArea = data.sapCode;
                })
            };

            $scope.clearArea = function () {
                $scope.detailInfo.inArea = "";
                $scope.detailInfo.sapInArea = "";
            };

            $scope.mandatoryFinish = function (billNo, billId, materialsNo, rowNo) {
                ybWidget.ShowMessage("确定要结单吗？", MESG_TYPE.Ask).then(function () {
                    var service = "device";
                    var reqUrl = "/deliveryInstruction/manualFinish";
                    var param = {
                        billNo: billNo,
                        materialsNo: materialsNo ? materialsNo : null,
                        rowNo: rowNo ? rowNo : null
                    };
                    ybHttp.Post(service, reqUrl, param).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        if (!!billId) {
                            getDetail(billId).then(function (data) {
                                if (!data) {
                                    return;
                                }
                                $scope.orderObj = data;
                                angular.forEach($scope.orderObj.detailList, function (item) {
                                    item.stateShow = $filter("ProgressStatus")(item.state, "inDepot");
                                    item.postingStateShow = $filter("ProgressStatus")(item.postingState, "posting");
                                });
                            });
                        }
                        getDataList();
                    });
                }, function () {
                });
            };

            $scope.saveData = function (isValid) {
                if (!isValid) {
                    $scope.submitted = true;
                    return;
                }
                var service = "device";
                var reqUrl = $scope.tabFlag.type == 0 ? '/deliveryInstruction/add' : '/deliveryInstruction/update';
                var param = angular.copy($scope.detailInfo);
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    getDataList(1);
                    $scope.changeTab(0);
                });
            };

            $scope.revoke = function (billId, item) {
                item.postingDisabled = true;
                var service = "device";
                var reqUrl = "/deliveryInstruction/revoke";
                var param = {};
                param.detailId = item.id;
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        item.postingDisabled = false;
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.viewDetail({id: billId });
                });
            };

            $scope.chongxiao = function (val) {
                ybWidget.DataSelector({
                    size: 'lg',
                    title: '过账记录',
                    url: '/deliveryInstruction/getDetailPostingRecord',
                    otherParams: { detailId: val },
                    isMultiSelect: true,
                    fields: [
                        { name: '零件编号', dataField: 'materialNo', width: "15%" },
                        { name: '零件中文名', dataField: 'materialName', width: "25%" },
                        { name: '内配零件凭证号', dataField: 'outVoucher', width: "20%" },
                        { name: '外配零件凭证号', dataField: 'inVoucher', width: "20%" },
                        { name: '过账数量', dataField: 'postingQty', width: "10%" },
                        { name: '行号', dataField: 'rowNo', width: "10%" },
                    ],
                }).then(function (data) {
                    ybWidget.ShowMessage("确定要冲销吗？", MESG_TYPE.Ask).then(function () {
                        var service = "device";
                        var reqUrl = "/deliveryInstruction/detailPostingRecordChargeOff";
                        ybHttp.Post(service, reqUrl, { chargeOffList: data }).then(function (resp) {
                            if (resp.code !== 0) {
                                ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                                return;
                            }
                            ybWidget.ShowToaster('success', '操作成功');
                        })
                    }, function () {})
                })
            };

            $scope.cancel = function () {
                $scope.changeTab(0);
            };


            $scope.inTbConf = {
                scrollWidth: 900,
                tableCol: [
                    {
                        name: "零件编号",
                        width: 150,
                        dataField: "materialNo",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "零件中文名",
                        width: 200,
                        dataField: "materialName",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "分类",
                        width: 100,
                        dataField: "materialType",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "单位",
                        width: 100,
                        dataField: "unit",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "入库数量",
                        width: 110,
                        dataField: "amount",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "储位",
                        width: 260,
                        dataField: "locationCode",
                        input: true,
                        inputType: "func"
                    },
                    {
                        name: "入库状态",
                        width: 130,
                        dataField: "stateShow",
                        input: false,
                        inputType: "",
                        isShow: false
                    }
                ]
            };
            $scope.inbound = function (item) {
                getDetail(item.id).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.orderObj = data;
                    angular.forEach($scope.orderObj.detailList, function (item) {
                        item.stateShow = $filter("ProgressStatus")(item.state, "inDepot");
                        item.locationCode = item.stockLocation; // 有默认储位，默认值为：默认储位
                    });
                    $scope.changeTab(3);
                });
            };
            $scope.selDepot = function (item) {
                var param = {
                    warehouseCode: $scope.orderObj.headerInfo.warehouseCode
                };
                ybWidget.DepotSelector(param).then(function (data) {
                    item.warehouseCode = data.warehouseCode;
                    item.areaCode = data.areaCode;
                    item.locationCode = data.locationCode;
                })
            };
            $scope.clearDepot = function (item) {
                item.warehouseCode = "";
                item.areaCode = "";
                item.locationCode = "";
            };
            $scope.inboundSubmit = function () {
                var service = "device";
                var reqUrl = "/warehouseInboundRecord/receive";
                var param = {
                    headerInfo: {
                        businessOrder: $scope.orderObj.headerInfo.deliveryOrder
                    },
                    detailList: []
                };
                var errorCount = 0;
                angular.forEach($scope.orderObj.detailList, function (item) {
                    var listRow = {};
                    listRow.materialNo = item.materialNo;
                    listRow.warehouseCode = item.warehouseCode;
                    listRow.areaCode = item.areaCode;
                    listRow.locationCode = item.locationCode;
                    item.locationErr = false;
                    if((item.state === 0 || item.state === 1) && !item.locationCode){
                        item.locationErr = true;
                        errorCount++;
                    }
                    param.detailList.push(listRow);
                });
                if(errorCount> 0){
                    return;
                }
                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                    getDataList();
                });
            };

            $scope.postBatch = function() {
                const selectedDatas = $scope.dataList.filter(od => od.isChecked);
                if (selectedDatas.length === 0) {
                    ybWidget.ShowToaster('error', '请选择需要过账的行');
                    return;
                }

                ybWidget.ShowMessage("确定要一键过账吗？", MESG_TYPE.Ask).then(function () {
                    var service = "device";
                    var reqUrl = "/deliveryInstruction/oneClickPosting";
                    ybHttp.Post(service, reqUrl, { idList: selectedDatas.map(sd => sd.id) }).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }

                        const respValTmp = resp.value || [];
                        if (respValTmp.length > 0) {
                            ybWidget.ShowMessage(respValTmp.join("<br/>"),  MESG_TYPE.Error, {isHtml: true})
                        } else {
                            ybWidget.ShowToaster('success', '操作成功');
                        }
                        
                        getDataList();
                    })
                }, function () {})
            };

            (function () {
                getDataList();
                $scope.setFixedWidth();
                UserContextService.SetBtnPermission(setBtnPermission);
            })();
        }])
    ;
})(window, window.angular);